package com.lambkit.node;

import com.alibaba.fastjson.JSON;
import com.lambkit.util.ServletRequestKit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class NodeHttpAction {
	
	private HttpServletRequest request;
	private HttpServletResponse response;
	private String rawData;
	private NodeHttpParam param;
	
	public NodeHttpAction(HttpServletRequest request, HttpServletResponse response) {
		
		this.request = request;
		this.response = response;
		this.rawData = null;
		this.param = null;
	}
	
	/**
	 * 执行action
	 */
	public void run() {
		
	}
	
	/**
	 * 在对 Controller 回收使用场景下，如果继承类中声明了属性，则必须要
	 * 覆盖此方法，调用父类的 clear() 方法并清掉自身的属性，例如：
	 * 
	 * super._clear_();
	 * this.xxx = null;
	 */
	protected void _clear_() {
		request = null;
		response = null;
		rawData = null;
		param = null;
	}
	
	/**
	 * 获取 http 请求 body 中的原始数据，通常用于接收 json String 这类数据<br>
	 * 可多次调用此方法，避免掉了 HttpKit.readData(...) 方式获取该数据时多次调用
	 * 引发的异常
	 * @return http 请求 body 中的原始数据
	 */
	public String getRawData() {
		if (rawData == null) {
			rawData = ServletRequestKit.readData(request);
		}
		return rawData;
	}
	
	public NodeHttpParam getParam() {
		if(param == null) {
			param = JSON.parseObject(getRawData(), NodeHttpParam.class);
		}
		return param;
	}
	
	public HttpServletRequest getRequest() {
		return request;
	}
	
	public HttpServletResponse getResponse() {
		return response;
	}
	
	public void setHttpServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	public void setHttpServletResponse(HttpServletResponse response) {
		this.response = response;
	}
}
